﻿/*
*┌────────────────────────────────────────────────┐
*│　描    述：HttpService                                                   
*│　作    者： (Jxw)                                             
*│　版    本：1.0     
*│　功能描述：                                          
*│　创建时间：2021/4/20 10:42:54                        
*└────────────────────────────────────────────────┘
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Utility
{
    /// <summary>
    /// http连接基础类，负责底层的http通信
    /// </summary>
    public class HttpService
    {
        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            //直接确认，否则打不开    
            return true;
        }
        public static string Post(string content, string url, int timeout, string token)
        {
            System.GC.Collect();//垃圾回收，回收没有正常关闭的http连接
            string result = "";//返回结果
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream reqStream = null;
            try
            {
                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.Timeout = timeout * 1000;

                request.ContentType = "application/json";
                request.ContentLength = Encoding.UTF8.GetByteCount(content);
                request.Headers.Add("Authorization", "Bearer" + token);//请求头token验证

                //往服务器写入数据
                reqStream = request.GetRequestStream();
                StreamWriter myStreamWriter = new StreamWriter(reqStream, Encoding.GetEncoding("gb2312"));
                myStreamWriter.Write(content);
                myStreamWriter.Close();

                //获取服务端返回
                response = (HttpWebResponse)request.GetResponse();
                //获取服务端返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }

        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData">post数据</param>
        /// <returns></returns>
        public static string PostResponse( string url, string postData)
        {
            if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

            HttpContent httpContent = new StringContent(postData);
            httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            httpContent.Headers.ContentType.CharSet = "utf-8";
            //if (!string.IsNullOrEmpty(header))
            //{
            //    httpContent.Headers.Add("Authorization", "Bearer" + header);
            //}

            HttpClient httpClient = new HttpClient();

            HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;

            if (response.IsSuccessStatusCode)
            {
                string result = response.Content.ReadAsStringAsync().Result;
                return result;
            }

            return null;
        }

        /// <summary>
        /// 万达post请求   要求带上请求头  appCode、sign和Content-Type
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData">post数据</param>
        /// <returns></returns>
        public static string PostResponse(string url, string postData, string appCode, string sign)
        {
            System.GC.Collect();//垃圾回收，回收没有正常关闭的http连接
            string result = "";//返回结果
            HttpWebRequest request = null;
            HttpWebResponse response = null;
            Stream reqStream = null;
            try
            {

                //设置最大连接数
                ServicePointManager.DefaultConnectionLimit = 200;
                //设置https验证方式
                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                {
                    ServicePointManager.ServerCertificateValidationCallback =
                            new RemoteCertificateValidationCallback(CheckValidationResult);
                }

                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                //request.Timeout = 2000;   //连接的时间  2s
                //request.ReadWriteTimeout = 60000; //读取流的超时时间  60s


                request.ContentType = "application/json";
                request.Headers.Add("appCode", appCode);
                request.Headers.Add("sign", sign);
                request.Headers.Add("Content", "application/json");

                byte[] byteArray = Encoding.UTF8.GetBytes(postData); //转化
                request.ContentLength= byteArray.Length;
                reqStream = request.GetRequestStream();
                reqStream.Write(byteArray, 0, byteArray.Length);
                reqStream.Close();
                
                //reqStream.Write(byteArray, 0, byteArray.Length);//写入参数
                //reqStream.Close();
                //StreamWriter myStreamWriter = new StreamWriter(reqStream, Encoding.GetEncoding("gb2312"));
                //StreamWriter myStreamWriter = new StreamWriter(reqStream, Encoding.GetEncoding("gb2312"));
                //myStreamWriter.Write(postData);
                //myStreamWriter.Close();

                //获取服务端返回
                response = (HttpWebResponse)request.GetResponse();
                //获取服务端返回数据
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                result = sr.ReadToEnd().Trim();
                sr.Close();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                //关闭连接和流
                if (response != null)
                {
                    response.Close();
                }
                if (request != null)
                {
                    request.Abort();
                }
            }
            return result;
        }


        //public static string PostResponse1(string url, string postData, string appCode, string sign)
        //{
        //    try
        //    {
        //        if (url.StartsWith("https"))
        //            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

        //        HttpContent httpContent = new StringContent(postData);
        //        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
        //        httpContent.Headers.ContentType.CharSet = "utf-8";
        //        if (!string.IsNullOrEmpty(appCode) && !string.IsNullOrEmpty(sign))
        //        {
        //            httpContent.Headers.Add("appCode", appCode);
        //            httpContent.Headers.Add("sign", sign);
        //            httpContent.Headers.Add("Content", "application/json");
        //        }

        //        HttpClient httpClient = new HttpClient();
        
        //        HttpResponseMessage response = httpClient.PostAsync(url, httpContent).Result;
        //        response.EnsureSuccessStatusCode();//用来抛异常的
        //        //LogUtility.Debug("HttpService/PostResponse", response.ToString());
        //        if (response.IsSuccessStatusCode)
        //        {
        //            string result = response.Content.ReadAsStringAsync().Result;
        //            return result;
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        throw e;
        //    }

        //    return null;
        //}




        public static string PostWebRequest(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/x-www-form-urlencoded";
                webReq.CookieContainer = new CookieContainer();
                webReq.ContentLength = byteArray.Length;

                webReq.Timeout = 2000;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();
                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), dataEncode);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {
                LogUtility.Error("PostWebRequest", "Post异常,原因:" + ex.Message + ",url=" + postUrl);
            }
            return ret;
        }


        /// <summary>
        /// 获取get请求
        /// </summary>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string SendDataByGET(string Url)
        {
            string retString = string.Empty;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "get";
                request.ContentType = "text/html;charset=UTF-8";
                request.Timeout = 3000;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();
            }
            catch (Exception ex)
            {
                LogUtility.Error("SendDataByGET", "获取get请求失败,原因:" + ex.Message);
                retString = null;
            }
            return retString;
        }

    }
}
